package com.web44.ssm.web;

import com.web44.ssm.utils.ResponseVo;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @Title: UploadController
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/2/18 14:43
 */
@RestController
@RequestMapping("upload")
public class UploadController {

    @PostMapping("file")
    public ResponseVo uploadWeb(@RequestParam("face") MultipartFile file, HttpServletRequest request) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);

        // 当前文件夹
        String projectPath = request.getServletContext().getRealPath("/images");
        // 年/月/日
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String datePath = now.format(formatter);
        // 设置文件的名字
        String filename = UUID.randomUUID().toString().replaceAll("-","");
        String realname = filename+"."+extension;
        // 目标位置
        File dest = new File(projectPath+"/"+datePath);
        if(!dest.exists()) {
            dest.mkdirs();
        }
        dest = new File(dest,realname);
        file.transferTo(dest);
        return ResponseVo.ok("上传成功","/images/"+datePath+"/"+realname);
    }
}
